package com.lu.methodref;

import org.junit.Test;

import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author 陆小根
 * date: 2022/07/10
 * Description:
 *
 * 一、构造器引用
 *    和 方法引用类似，函数式接口的抽象方法的形参列表和构造器的形参列表一致。
 *    抽象方法的返回值类型即为构造器所属的类的类型
 *
 * 二、数组引用
 *    可以把数组看做一个特殊的类，则写法与构造器引用一致。
 *
 *
 *
 *
 */

public class ConstructRefTest {

  // 构造器引用
  // Supplier 中的 T get()
  // Employee 中空参构造器: Employee()
  @Test
  public void test1() {

    Supplier<Employee> sup = new Supplier<Employee>() {
      @Override
      public Employee get() {
        return new Employee();
      }
    };
    sup.get();

    System.out.println("*************************");

    Supplier<Employee> sup1 = () -> new Employee();
    sup1.get();
    System.out.println("***************************");

    Supplier<Employee> sup2 = Employee::new;
    sup2.get();

  }

  // Function 中的 apply(T t)
  @Test
  public void test2() {
    Function<Integer,Employee> func1 = id -> new Employee(id);
    Employee employee = func1.apply(1001);
    System.out.println(employee);

    System.out.println("*****************************");

    Function<Integer,Employee> func2 = Employee::new;
    Employee emp2 = func2.apply(1002);
    System.out.println(emp2);
  }

  // BiFunction 中 R apply(T t)
  @Test
  public void test3() {
    BiFunction<Integer,String,Employee> func1 = (id,name) -> new Employee(id, name);
    Employee emp1 = func1.apply(1001, "张三");
    System.out.println(emp1);

    System.out.println("****************************");
    BiFunction<Integer,String,Employee> func2 = Employee :: new;
    Employee tom = func2.apply(1002, "Tom");
    System.out.println(tom);
  }

  // 数组引用
  // Function 中的 R apply(T t)
  @Test
  public void test() {
    Function<Integer,String[]> func1 = length -> new String[length];
    String[] arr1 = func1.apply(5);
    System.out.println(Arrays.toString(arr1));

    System.out.println("*********************");

    Function<Integer,String[]> func2 = String[]::new;
    String[] arr2 = func2.apply(10);
    System.out.println(Arrays.toString(arr2));
  }
}
